<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-partRead>
            <el-button :disabled="!partReadDisabled" @click="partRead()"
              >标为已读</el-button
            >
          </template>
          <template v-slot:filter-allRead>
            <el-button :disabled="notReadCount <= 0" @click="allRead()"
              >全部标为已读</el-button
            >
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        ref="messageTableRef"
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-content="scope">
          <span
            ><span v-for="(item, index) in scope.row.content" :key="index">
              <span
                v-if="
                  (item != null && item.type === 1) ||
                  (item.type === 2 && (item.url == '' || item.url == undefined))
                "
                >{{ item.content }}</span
              >
              <span
                v-else
                class="message-content"
                @click="turnPage(item, scope.row)"
                >{{ item.content }}</span
              >
            </span>
          </span>
        </template>
        <template v-slot:col-title="scope">
          <div class="title">
            <div
              class="badge"
              :class="scope.row.haveRead === 1 ? 'badge-color' : ''"
            ></div>
            <span
              :class="
                scope.row.level === 2
                  ? 'level2'
                  : scope.row.level === 1
                  ? 'level1'
                  : 'level0'
              "
              >{{ scope.row.title }}</span
            >
          </div>
        </template>
      </table-container>
    </div>
    <!-- 详情弹窗 -->
    <page-dialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- form -->
      <basic-information :info="infoList">
        <template v-slot:basic-title>
          <span
            :class="
              infoList.row.level === 2
                ? 'level2'
                : infoList.row.level === 1
                ? 'level1'
                : 'level0'
            "
            >{{ infoList.data.title }}</span
          >
        </template>
        <template v-slot:basic-content>
          <span
            ><span v-for="(item, index) in infoList.data.content" :key="index">
              <span
                v-if="
                  (item != null && item.type === 1) ||
                  (item.type === 2 && (item.url == '' || item.url == undefined))
                "
                >{{ item.content }}</span
              >
              <span
                v-else
                class="message-content"
                @click="turnPage(item, infoList.data)"
                >{{ item.content }}</span
              >
            </span></span
          >
        </template>
      </basic-information>
    </page-dialog>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="messageManager">
import {
  postMessageReceivePage,
  updateReadStatusById,
  updateReadStatusBatch,
  updateReadStatusAll,
  getMessageReceiveCountByStatus,
} from '@/api/message'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { messageReceiveGetById } from '@/api/message'
const { proxy } = getCurrentInstance()
// 当前登录人未读消息数量
const notReadCount = ref(0)
const infoList = ref({
  data: {},
  row: {},
  fieldList: [
    { label: '标题', value: 'title', type: 'slot' },
    { label: '是否已读', value: 'haveReadValue' },
    { label: '查看时间', value: 'readTime' },
    { label: '发送人', value: 'sendUserName' },
    { label: '接收时间', value: 'createTime' },
    { label: '内容', value: 'content', type: 'slot' },
  ],
})
const dialogInfo = ref({
  title: '消息详情',
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [{ label: '关闭', type: '', icon: '', event: close, show: true }],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      userId: {
        asTbName: 'message_receive',
        columnName: 'user_id',
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: proxy.$store.state.user.userInfo.user.id,
      },
      type: {
        queryType: 'IN',
        value: 1,
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'partRead',
      show: proxy.$permission('message:partRead'),
    },
    {
      type: 'slot',
      value: 'allRead',
      show: proxy.$permission('message:partRead'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '详情',
        event: dialogInfoShow,
        show: proxy.$permission('message:detail'),
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  exportId: '',
  title: '',
})
const detailListInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  data: {},
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const partReadDisabled = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.haveRead !== 0).length
  )
})
onActivated(() => {
  // 解决出现提示框 点击到另外页面 再次返回 提示框没隐藏
  const nodeList = document.querySelectorAll('.el-popper')
  for (var i = 0; i < nodeList.length; i++) {
    nodeList[i].style.display = 'none'
  }
})
onMounted(() => {
  setData()
})
function setData() {
  let obj = {
    content: {
      label: '消息内容',
      value: 'content',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    haveReadValue: {
      label: '状态',
      value: 'haveReadValue',
      componentType: 'select-model',
      code: 'yes_or_no',
      show: false,
      hidden: true,
    },
    messageTypeValue: {
      label: '消息类型',
      value: 'messageTypeValue',
      componentType: 'select-model',
      code: 'message_type',
      show: false,
      hidden: true,
    },
    readTime: {
      label: '查看时间',
      value: 'readTime',
      componentType: 'dateTime',
      show: false,
      hidden: true,
    },
    title: {
      label: '标题',
      value: 'title',
      type: 'slot',
      componentType: 'input',
      hidden: false,
      show: true,
    },
    sendUserName: {
      label: '发送人',
      value: 'sendUserName',
      asValue: 'sendUserId',
      componentType: 'select-user',
      highlightRow: true,
      checkBox: false,
      show: false,
      hidden: true,
    },
    reminderTypeValue: {
      label: '提示方式',
      value: 'reminderTypeValue',
      componentType: 'select-model',
      code: 'reminder_type',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
//全部标为已读
function allRead() {
  updateReadStatusAll().then((res) => {
    if (res.success) {
      getList()
    }
  })
}
function partRead() {
  if (
    tableInfo.value.selections != null &&
    tableInfo.value.selections.length > 0
  ) {
    let ids = []
    tableInfo.value.selections.map((val) => {
      if (val.haveRead == 0) {
        ids.push(val.id)
      }
    })
    if (ids.length === 0) {
      proxy.$message.warning({
        message: '无未读消息！',
        showClose: true,
        duration: 3000,
      })
      tableInfo.value.selections.forEach((value) => {
        proxy.$refs['messageTableRef'].toggleRowSelection(value, false)
      })
      tableInfo.value.selections = []
      return
    }
    updateReadStatusBatch(ids).then((res) => {
      if (res.success) {
        getList()
        tableInfo.value.selections.forEach((value) =>
          proxy.$refs['messageTableRef'].toggleRowSelection(value, false)
        )
        tableInfo.value.selections = []
      }
    })
  } else {
    proxy.$message.warning({
      message: '请选择数据！',
      showClose: true,
      duration: 3000,
    })
  }
}
function close() {
  dialogInfo.value.visible = false
}
function dialogInfoShow(row) {
  messageReceiveGetById(row.id).then((res) => {
    if (res.success) {
      infoList.value.data = res.data
      if (
        infoList.value.data != null &&
        infoList.value.data.content != null &&
        infoList.value.data.content != ''
      ) {
        let temp = JSON.parse(infoList.value.data.content)
        // let content="";
        // temp.forEach(val=>{
        //   content=content+val.content;
        // })
        infoList.value.data.content = temp
      }
      if (infoList.value.data.haveReadValue === '否') {
        updateReadStatus(infoList.value.data.id)
      }
      infoList.value.row = row
      dialogInfo.value.visible = true
    }
  })
}
//跳转页面
function turnPage(val, row) {
  let url = val.url
  let name = ''
  let routes = proxy.$store.state.permission.routes
  routes.map((item) => {
    if (item.children && item.children.length) {
      item.children.map((i) => {
        if (i.url === url) {
          name = url
        }
      })
    }
  })

  if (name) {
    proxy.$router.push(url)
    proxy.$store.dispatch('settings/toPage', val)
    dialogInfo.value.visible = false
    if (row.haveRead === 0) {
      updateReadStatus(row.id)
    }
  } else {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '你没有相应的菜单权限',
    })
  }
}
//修改消息是否已读
function updateReadStatus(id) {
  updateReadStatusById(id).then((res) => {
    if (res.success) {
      getList()
    }
  })
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}
  let arr = [
    {
      fieldName: 'userId',
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: proxy.$store.state.user.userInfo.user.id,
    },
  ]
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  // proxy.$nextTick(() => {
  tableInfo.value.refresh = Math.random()
  // })
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
  getNotReadCount()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      if (data != null) {
        data.forEach((val) => {
          val.content = JSON.parse(val.content)
        })
        tableInfo.value.data = data
      }
      break
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey: 'messageManager-com.slip.spd.entity.vo.message.MessageReceiveVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      if ('system_admin' === proxy.$store.state.user.userInfo.user.type) {
        _filterInfo.query.queryMap = {
          ...searchInfo.queryMap,
        }
      } else {
        _filterInfo.query.queryMap = {
          ...searchInfo.queryMap,
          ..._filterInfo.query.queryMap,
        }
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = postMessageReceivePage
      getList()
      getNotReadCount()
    }
  })
}
function getNotReadCount() {
  let params = {
    queryMap: {
      userId: {
        asTbName: 'message_receive',
        columnName: 'user_id',
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: proxy.$store.state.user.userInfo.user.id,
      },
      type: {
        queryType: 'IN',
        value: 1,
      },
    },
    customizeUserVO: filterInfo.value.query.customizeUserVO,
  }
  getMessageReceiveCountByStatus(params).then((res) => {
    if (res && res.success) {
      if (res.data && res.data.length) {
        let arr = res.data.filter((item) => item.haveRead == 0)
        if (arr && arr.length) {
          notReadCount.value = arr[0].orderCount || 0
        } else {
          notReadCount.value = 0
        }
      } else {
        notReadCount.value = 0
      }
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function tableRowClassName({ row }) {
  if (row.level === 0) {
    return 'level0-bg'
  } else if (row.level === 1) {
    return 'level1-bg'
  } else if (row.level === 2) {
    return 'level2-bg'
  }
  return ''
}
</script>

<style scoped lang="scss">
.title {
  display: flex;
  align-items: center;
  justify-content: center;
  .badge {
    width: 10px;
    height: 10px;
    border-radius: 5px;
    background: #f56c6c;
    margin: 0 5px 2px 0;
  }
  .badge-color {
    background: transparent;
  }
}
</style>
